package mars.ns.selectors

import mars.ns.core._
import scala.util.Random
import dummy.world.Family

/**
 * This trait selects random nodes and connects random nodes
 */
trait RandomSelection[T <: Node] extends NodeSelection[T] {
    override def selectNode(network: Network[T]): T = {
        val nodes = network.getNodes()
        val index = Random.nextInt(nodes.length)
        return nodes.apply(index)
    }
    override def connect(network: Network[T], node: T) :Set[Link] ={
		if(this.avoidRecursion == MAX_RECURSION){
    		throw new Error("Couldn't connect two nodes in the resting network");
    	}
		val tmpAR : Int = this.avoidRecursion
		this.avoidRecursion = 0
    	var node2 = selectNode(network)
    	val connected = node.getLinkedObjects()
    	while (connected.contains(node2)){
    		this.avoidRecursion += 1
    		if(this.avoidRecursion == (connected.size * 2)){
    			this.avoidRecursion = tmpAR + 1
    			connect(network, selectNode(network))        		  
    		}
    		node2 = selectNode(network)        	  
    	}
    	this.avoidRecursion = 0;
    	node.addDoubleLink(node2, new DefaultLink)
    	return node.getLinksTo(node2)
    }
}